import Vue from 'vue'
import KeyboardNumSimple from './KeyboardNumSimple.vue'

let KeyboardNumSimpleConstructor = Vue.extend(KeyboardNumSimple)

let keyboardNumSimple = new KeyboardNumSimpleConstructor({
  el: document.createElement('div')
})
keyboardNumSimple.isPopover = true

function focusInputFactory ({el, binding}) {
  return function () {
    keyboardNumSimple.showPopover = true
    keyboardNumSimple.popoverPosition = binding.arg
    keyboardNumSimple.directiveRect = el.getBoundingClientRect()
  }
}

function resetInput () {
  keyboardNumSimple.showPopover = false
}

window.focusInput = null

let keyboard = {}
keyboard.install = (Vue, options) => {
  Vue.component('KeyboardNumSimple', KeyboardNumSimple)
  document.body.appendChild(keyboardNumSimple.$el)

  document.body.addEventListener('focus', (ev) => {
    if (ev.target.tagName === 'INPUT' &&
      (ev.target.type === 'text' ||
       ev.target.type === 'password' ||
       ev.target.type === 'email' ||
       ev.target.type === 'tel' ||
       ev.target.type === 'url' ||
       ev.target.type === 'number')) {
      window.focusInput = ev.target
    } else if (ev.target.tagName === 'TEXTAREA') {
      window.focusInput = ev.target
    }
  }, true)

  Vue.directive('num-keyboard', {
    bind (el, binding, vnode) {
      el.focusInputHandle = focusInputFactory({el, binding})
      el.dismissHandle = function (e) {
        if (el && !el.contains(e.target) && !keyboardNumSimple.isMineElement(e.target)) {
          keyboardNumSimple.showPopover = false
        }
      }

      el.addEventListener('focus', el.focusInputHandle)
      document.addEventListener('click', el.dismissHandle, true)
    },
    unbind (el) {
      el.removeEventListener('focus', el.focusInputHandle)
      document.removeEventListener('click', el.dismissHandle, true)
      resetInput()
    }
  })
}

export default keyboard
